package cn.tedu.admin.account.service.impl;

import cn.tedu.admin.account.dao.persist.repository.IUserRepository;
import cn.tedu.admin.account.dao.persist.repository.IUserRoleRepository;
import cn.tedu.admin.account.pojo.entity.User;
import cn.tedu.admin.account.pojo.entity.UserRole;
import cn.tedu.admin.account.pojo.param.UserAddNewParam;
import cn.tedu.admin.account.pojo.param.UserUpdateInfoParam;
import cn.tedu.admin.account.pojo.vo.UserListItemVO;
import cn.tedu.admin.account.pojo.vo.UserStandardVO;
import cn.tedu.admin.account.service.IUserService;
import cn.tedu.common.enumerator.ServiceCode;
import cn.tedu.common.ex.ServiceException;
import cn.tedu.common.pojo.vo.PageData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    IUserRepository iUserRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    IUserRoleRepository iUserRoleRepository;

    @Override
    public void addNew(UserAddNewParam userAddNewParam) {

        //检查用户名是否被占用
        String username = userAddNewParam.getUsername();
        int count = iUserRepository.countByUsername(username);
        if (count > 0){
            String message = "添加用户失败,用户名被占用";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        //检查手机号是否被占用
        String phone = userAddNewParam.getPhone();
        count= iUserRepository.countByPhone(phone);
        if (count > 0){
            String message = "添加用户失败,手机号被占用";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        //检查邮箱是否被占用
        String email = userAddNewParam.getEmail();
        count = iUserRepository.countByEmail(email);
        if (count > 0){
            String message = "添加用户失败,邮箱被占用";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        //将参数对象调用insert方法插入到数据库user表中
        User user = new User();
        BeanUtils.copyProperties(userAddNewParam,user);
        user.setLoginNum(0);
        String password = userAddNewParam.getPassword();
        String encodePassword = passwordEncoder.encode(password);
        user.setPassword(encodePassword);
        int rows = iUserRepository.insert(user);
        if (rows != 1){
            String message = "服务器忙,请稍后再试!";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        //将参数对象中的角色ID的数组插入到数据库用户角色表中（用户与角色的关联数据）
        Long[] roleIds = userAddNewParam.getRoleIds();
        List<UserRole> userRoleList = new ArrayList<>();
        for (Long roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleList.add(userRole);
        }
        rows = iUserRoleRepository.insertBatch(userRoleList);
        if (rows < 1){
            String message = "服务器忙,请稍后再试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT,message);
        }



    }

    //修改用户密码
    @Override
    public void updatePassword(Long userId, String password) {
        String newPassword = passwordEncoder.encode(password);
        User user = new User();
        user.setId(userId);
        user.setPassword(newPassword);
        int rows = iUserRepository.updateById(user);
        if (rows != 1){
            String message = "服务器忙,请稍后再试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
        }
    }

    //修改用户头像
    @Override
    public void updateUserurl(Long userId, String userUrl) {
        User user = new User();
        user.setId(userId);
        user.setUserUrl(userUrl);
        int rows = iUserRepository.updateById(user);
        if (rows != 1){
            String message = "服务器忙,请稍后再试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
        }
    }

    //修改用户手机号
    @Override
    public void updatePhone(Long userId, String phoneNumber) {
        int count = iUserRepository.countByPhone(phoneNumber);
        if (count > 1){
            String message = "修改用户手机号失败,手机号被占用";
            throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
        }
        User user = new User();
        user.setId(userId);
        user.setPhoneNumber(phoneNumber);
        int rows = iUserRepository.updateById(user);
        if (rows != 1){
            String message = "服务器忙,请稍后再试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
        }


    }

    //修改用户基本信息
    @Override
    public void updateInfo(Long userId, UserUpdateInfoParam userUpdateInfoParam) {
        User user = new User();
        user.setId(userId);
        BeanUtils.copyProperties(userUpdateInfoParam,user);
        int rows = iUserRepository.updateById(user);
        if (rows != 1){
            String message = "服务器忙,请稍后再试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
        }
    }

    //启用用户
    @Override
    public void setEnable(Long userId) {
        updateEnableById(userId, ENABLE_STATE_ON);
    }

    //禁用用户
    @Override
    public void setDisable(Long userId) {
        updateEnableById(userId, ENABLE_STATE_OFF);
    }

    //根据id查询用户
    @Override
    public UserStandardVO getStandardById(Long userId) {
        UserStandardVO currentUser = iUserRepository.getStandardById(userId);
        if (currentUser == null) {
            String message = "获取用户详情失败，尝试访问的用户数据不存在！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        return currentUser;
    }

    @Override
    public PageData<UserListItemVO> list(Integer pageNum) {
        return iUserRepository.list(pageNum, 10);
    }


    /**
     * 修改用户的启用状态
     *
     * @param id     用户ID
     * @param enable 新的启用状态
     */
    private void updateEnableById(Long id, Integer enable) {
        if (id == 1) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        UserStandardVO queryResult = iUserRepository.getStandardById(id);
        if (queryResult == null) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        if (queryResult.getEnable().equals(enable)) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，当前用户已经处于"
                    + ENABLE_STATE_TEXT[enable] + "状态！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }

        User user = new User();
        user.setId(id);
        user.setIsEnable(enable);
        int rows = iUserRepository.updateById(user);
        if (rows != 1) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，服务器忙，请稍后再次尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

    }
}
